import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.pages.base_page import BasePage
from core.utils.i18n import t
from ui.styles.theme import Theme

class LoginPage(BasePage):
    def create_widgets(self):
        # 主容器 - 居中显示
        main_container = customtkinter.CTkFrame(self, fg_color="transparent")
        main_container.place(relx=0.5, rely=0.5, anchor="center")
        
        # 获取主题颜色
        fg_primary = Theme.get_color('fg_primary')
        fg_tertiary = Theme.get_color('fg_tertiary')
        accent_color = Theme.get_color('accent')
        
        # 标题
        self.title_label = customtkinter.CTkLabel(
            main_container, 
            text=t("login.title"), 
            font=("Arial", 24, "bold"),
            text_color=fg_primary,
            bg_color="transparent"
        )
        self.title_label.pack(pady=10)
        
        self.subtitle_label = customtkinter.CTkLabel(
            main_container,
            text=t("login.subtitle"), 
            font=("Arial", 12),
            text_color=fg_tertiary,
            bg_color="transparent"
        )
        self.subtitle_label.pack(pady=5)
        
        # 登录表单容器
        self.login_frame = customtkinter.CTkFrame(main_container, fg_color=("gray95", "gray20"))
        self.login_frame.pack(pady=20, padx=50, fill="x", ipadx=20, ipady=20)
        
        # 用户名输入
        username_label = customtkinter.CTkLabel(self.login_frame, text=t("login.username"), font=("Arial", 12))
        username_label.grid(row=0, column=0, padx=5, pady=12, sticky="e")
        
        self.username_entry = customtkinter.CTkEntry(
            self.login_frame, 
            width=250,
            height=35,
            font=("Arial", 12)
        )
        self.username_entry.grid(row=0, column=1, padx=5, pady=12, sticky="w")
        self.username_entry.focus()
        
        # 密码输入
        password_label = customtkinter.CTkLabel(self.login_frame, text=t("login.password"), font=("Arial", 12))
        password_label.grid(row=1, column=0, padx=5, pady=12, sticky="e")
        
        # 密码输入框和可视化切换按钮
        password_frame = customtkinter.CTkFrame(self.login_frame, fg_color="transparent")
        password_frame.grid(row=1, column=1, padx=5, pady=12, sticky="w")
        
        self.password_entry = customtkinter.CTkEntry(
            password_frame, 
            width=220,
            height=35,
            show="•", 
            font=("Arial", 12)
        )
        self.password_entry.pack(side="left")
        
        self.password_visible = False
        self.password_toggle_btn = customtkinter.CTkButton(
            password_frame,
            text="👁",
            width=35,
            height=35,
            font=("Arial", 12),
            command=self.toggle_password_visibility,
            fg_color="transparent",
            hover_color=("gray80", "gray30")
        )
        self.password_toggle_btn.pack(side="left", padx=5)
        
        # 记住我和忘记密码行
        remember_forgot_frame = customtkinter.CTkFrame(self.login_frame, fg_color="transparent")
        remember_forgot_frame.grid(row=2, column=1, padx=5, pady=5, sticky="w")
        
        self.remember_me = tk.BooleanVar()
        self.remember_check = customtkinter.CTkCheckBox(
            remember_forgot_frame, 
            text=t("login.remember_me"),
            variable=self.remember_me,
            font=("Arial", 11)
        )
        self.remember_check.pack(side="left")
        
        # 忘记密码链接
        forgot_password_btn = customtkinter.CTkButton(
            remember_forgot_frame,
            text="忘记密码？",
            command=self.show_forgot_password,
            fg_color="transparent",
            hover_color=("gray80", "gray30"),
            text_color=("blue", "lightblue"),
            font=("Arial", 11)
        )
        forgot_password_btn.pack(side="left", padx=(20, 0))
        
        # 绑定回车键
        self.username_entry.bind('<Return>', lambda e: self.password_entry.focus())
        self.password_entry.bind('<Return>', lambda e: self.login())
        
        # 按钮框架
        self.button_frame = customtkinter.CTkFrame(self.login_frame, fg_color="transparent")
        self.button_frame.grid(row=3, column=0, columnspan=2, pady=20)
        
        # 登录按钮
        self.login_btn = customtkinter.CTkButton(
            self.button_frame, 
            text=t("login.sign_in"), 
            command=self.login,
            width=150,
            height=40,
            font=("Arial", 14, "bold"),
            fg_color=accent_color,
            hover_color="#E55A2B",
            corner_radius=10
        )
        self.login_btn.grid(row=0, column=0, padx=10)
        
        # 注册按钮
        self.register_btn = customtkinter.CTkButton(
            self.button_frame, 
            text=t("login.create_account"), 
            command=self.show_register,
            width=150,
            height=40,
            font=("Arial", 14),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=10
        )
        self.register_btn.grid(row=0, column=1, padx=10)
        
        # 底部链接
        self.bottom_frame = customtkinter.CTkFrame(main_container, fg_color="transparent")
        self.bottom_frame.pack(pady=10)
        
        self.no_account_label = customtkinter.CTkLabel(
            self.bottom_frame,
            text=t("login.no_account"),
            font=("Arial", 11),
            text_color=fg_tertiary
        )
        self.no_account_label.pack(side="left")
        
        self.sign_up_btn = customtkinter.CTkButton(
            self.bottom_frame,
            text=t("login.sign_up_now"),
            command=self.show_register,
            fg_color="transparent",
            hover_color=("gray80", "gray30"),
            text_color=("blue", "lightblue"),
            font=("Arial", 11)
        )
        self.sign_up_btn.pack(side="left", padx=5)
        
        # 游客浏览选项
        self.guest_frame = customtkinter.CTkFrame(main_container, fg_color="transparent")
        self.guest_frame.pack(pady=20)
        
        self.browse_guest_label = customtkinter.CTkLabel(
            self.guest_frame,
            text=t("login.browse_guest"),
            font=("Arial", 11),
            text_color=fg_tertiary
        )
        self.browse_guest_label.pack(side="left")
        
        self.guest_btn = customtkinter.CTkButton(
            self.guest_frame,
            text=t("login.continue_guest"),
            command=self.continue_as_guest,
            fg_color="transparent",
            hover_color=("gray80", "gray30"),
            text_color=("blue", "lightblue"),
            font=("Arial", 11)
        )
        self.guest_btn.pack(side="left", padx=5)
    
    def toggle_password_visibility(self):
        """切换密码可见性"""
        self.password_visible = not self.password_visible
        if self.password_visible:
            self.password_entry.configure(show="")
            self.password_toggle_btn.configure(text="🔒")
        else:
            self.password_entry.configure(show="•")
            self.password_toggle_btn.configure(text="👁")
    
    def login(self):
        """处理登录逻辑"""
        username = self.username_entry.get().strip()
        password = self.password_entry.get()
        
        # 输入验证
        if not username or not password:
            messagebox.showwarning(t("login.input_error"), t("login.enter_both"))
            return
        
        if len(username) < 3:
            messagebox.showwarning(t("login.input_error"), t("login.username_min_length"))
            return
        
        try:
            # 尝试登录
            remember = bool(self.remember_me.get())
            self.controller.auth_service.login(username, password, remember=remember)
            
            # 登录成功
            messagebox.showinfo(t("login.success"), t("login.welcome_back", username=username))
            
            # 更新购物车用户ID
            self.controller.update_cart_user()
            
            # 跳转到商品页面
            self.controller.show_page("ProductPage")
            
        except Exception as e:
            # 登录失败
            messagebox.showerror(t("login.login_failed"), str(e))
            self.password_entry.delete(0, tk.END)
            self.password_entry.focus()
    
    def show_register(self):
        """跳转到注册页面"""
        self.controller.show_page("RegisterPage")
    
    def continue_as_guest(self):
        """以游客身份继续浏览"""
        messagebox.showinfo(t("login.guest_mode"), t("login.guest_message"))
        self.controller.show_page("ProductPage")
    
    def show_forgot_password(self):
        """显示忘记密码对话框"""
        from ui.components.forgot_password_dialog import ForgotPasswordDialog
        dialog = ForgotPasswordDialog(self, self.controller.auth_service)
        if dialog.show():
            # 密码重置成功，提示用户登录
            messagebox.showinfo(t("common.tip"), t("login.password_changed_tip"))
    
    def update_data(self):
        """更新页面数据（如果需要）"""
        # 清空输入框
        self.username_entry.delete(0, tk.END)
        self.password_entry.delete(0, tk.END)
        
        # 重置密码可见性
        if self.password_visible:
            self.toggle_password_visibility()
        
        self.username_entry.focus()
    
    def refresh_language(self):
        """刷新语言显示"""
        try:
            # 更新标题和副标题
            self.title_label.configure(text=t("login.title"))
            self.subtitle_label.configure(text=t("login.subtitle"))
            
            # 更新标签
            username_label = self.login_frame.winfo_children()[0]  # 第一个是标签
            username_label.configure(text=t("login.username"))
            
            password_label = self.login_frame.winfo_children()[3]  # 密码标签
            password_label.configure(text=t("login.password"))
            
            # 更新复选框
            self.remember_check.configure(text=t("login.remember_me"))
            
            # 更新按钮
            self.login_btn.configure(text=t("login.sign_in"))
            self.register_btn.configure(text=t("login.create_account"))
            
            # 更新底部链接
            self.no_account_label.configure(text=t("login.no_account"))
            self.sign_up_btn.configure(text=t("login.sign_up_now"))
            
            # 更新游客选项
            self.browse_guest_label.configure(text=t("login.browse_guest"))
            self.guest_btn.configure(text=t("login.continue_guest"))
            
        except Exception as e:
            from core.utils.logger import error
            error(f"Failed to refresh language in LoginPage: {e}")
